package slhs.tempo.TableAnalyzer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Stack;

public class TableStateMemento {
    private final Stack<ByteArrayOutputStream> tableDataHistoryStack;
    private Object tableData = null;
    private ByteArrayOutputStream bos;
    private ByteArrayInputStream bin;
    private ObjectOutputStream oos;
    private ObjectInputStream ois;

    public TableStateMemento() {
	tableDataHistoryStack = new Stack();
    }

    public void saveCurrentState(Object tableData) {

	try {
	    bos = new ByteArrayOutputStream();
	    oos = new ObjectOutputStream(bos);
	    oos.writeObject(tableData);
	    oos.close();
	} catch (Exception e) {
	    System.out.println("Table data could not be saved");
	    e.printStackTrace();
	}
	tableDataHistoryStack.push(bos);
    }

    public Object getLastState() {
	tableData = null;
	if (tableDataHistoryStack.isEmpty() == false) {
	    bos = tableDataHistoryStack.pop();
	    bin = new ByteArrayInputStream(bos.toByteArray());
	    try {
		ois = new ObjectInputStream(bin);
		tableData = ois.readObject();
	    } catch (Exception e) {
		e.printStackTrace();
	    }

	}

	return tableData;

    }

    public boolean isEmpty() {
	return tableDataHistoryStack.isEmpty();
    }

}
